from microbit import *
from time import sleep_us
from machine import time_pulse_us

class DS(object):
    def setPin(self, P):
        if P == 'J1':
            self.e = pin8
            self.t = pin1
        if P == 'J2':
            self.e = pin12
            self.t = pin2
        if P == 'J3':
            self.e = pin14
            self.t = pin13
        if P == 'J4':
            self.e = pin16
            self.t = pin15

    def get_distance(self, P, unit=0):
        self.setPin(P)
        self.e.read_digital()
        self.t.write_digital(1)
        sleep_us(10)
        self.t.write_digital(0)
        ts = time_pulse_us(self.e, 1, 25000)
        if ts < 0:
             return 9999999
        distance = ts * 9 / 6 / 58
        if unit == 0:
            return round(distance, 1)
        elif unit == 1:
            return distance / 254
        else :
            return 999999

distance = DS()